import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classnames from 'classnames'
import { useDispatch } from 'react-redux'
import { sendCode, login } from '@/store/action/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'

export default function Login() {
  const location = useLocation()
  const history = useHistory()
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)
  const onExtra = async () => {
    if (time > 0) return
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    try {
      await dispatch(sendCode(mobile))
      setTime(60)
      let title = setInterval(() => {
        setTime((time) => {
          if (time === 1) {
            clearInterval(title)
          }
          return time - 1
        })
      }, 1000)
      Toast.success('发送成功')
    } catch (err) {
      if (err.response) {
        Toast.info(err.response.data.message)
      } else {
        Toast.info('发送验证码过于频繁')
      }
    }
  }
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    async onSubmit(values) {
      await dispatch(login(values))
      Toast.success('登录成功', 1, null, false)
      const pathname = location.state ? location.state.from : '/home'
      console.log(pathname)
      history.replace(pathname)
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3-9]\d{9}$/, '手机格式错误'),
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
    errors,
    isValid,
    touched,
  } = formik
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>短信验证</h3>
        <form onSubmit={handleSubmit}>
          <div className="input-item">
            <Input
              placeholder="请输入手机号"
              value={mobile}
              name="mobile"
              onChange={handleChange}
              onBlur={handleBlur}
            ></Input>
            {touched.mobile && errors.mobile && (
              <div className="validate">{errors.mobile}</div>
            )}
          </div>
          <div className="input-item">
            <Input
              placeholder="请输入验证码"
              extra={time === 0 ? '获取验证码' : time + '后秒'}
              value={code}
              name="code"
              // 不显示记录框
              autoComplete="off"
              onChange={handleChange}
              onExtra={onExtra}
              onBlur={handleBlur}
            ></Input>
            {touched.code && errors.code && (
              <div className="validate">{errors.code}</div>
            )}
          </div>
          <button
            type="submit"
            className={classnames('login-btn', !isValid ? 'disabled' : '')}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
